//
//  UserAccount.swift
//  nimabi
//
//  Created by danny on 15/6/27.
//  Copyright © 2015年 DannyLiu. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {

    ///  借口调用令牌
    var access_token: String
    /// 令牌的有效时长
    var expires_in: NSTimeInterval
    
    /// 过期日期
    /// 程序创建人有5年有效期，普通用户有效期三天
    var expiresDate: NSDate
    /// 用户uid
    var uid: String
    /// 昵称名字
    var name: String?
    /// 用户头像地址(url),大图180x180像素
    var avatar_large: String?
    
    //  这个地方为啥不需要super init呢?
    init (dict: [String: AnyObject]){
        
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        uid = dict["uid"] as! String
        
        // 计算过期时间
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        
        
    }
    // 打印对象的信息
    override var description: String {
        let properties = ["access_token", "expires_in", "uid", "expiresDate", "name", "avatar_large"]
        return "\(self.dictionaryWithValuesForKeys(properties))"
        
    }
    
    // MARK:加载用户信息
    
    func loadUserInfo(finished: (account:UserAccount?, error:NSError?) -> ()){
        
        let params = ["access_token":access_token, "uid":uid]
        NetWorkingTools.sharedNetWorkingTools().GET("2/users/show.json", parameters: params, success: { (_, Json) -> Void in
            

            let dict = Json as! [String:AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            // 这个时候再进行归档 信息最全
            self.saveAccount()
            
            print("通知调用方,用户信息已经加载完成")
            // 通知调用方,加载信息完成
            finished(account: self, error: nil)
            }) { (_, error) -> Void in
                finished(account: nil, error: error)
        }
        
    }
    
    
    // MARK: 保存和加载文件
    ///  归档路径 在swift中的类常量 都是硬static来定义的
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    
    ///  将对象归档
    func saveAccount(){
    
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    /// 这里用类方法 而且返回值有可能是nil,因此用?表示可选
    class func loadAccount() -> UserAccount? {
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount {
            
            // 判断日期是否过期，根当前系统时间进行`比较`，低于当前系统时间，就认为过期
            // 过期日期`大于`当前日期，结果应该是降序
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        return nil
    }
    
    
    // MARK: 归档/解档的具体实现
    ///  解档的方法,不知道刀哥为何requeired,而且还带个问好(知道了,这是实现NSCoding的方法)
    required init? (coder aDcoder: NSCoder){
        access_token = aDcoder.decodeObjectForKey("access_token") as! String
        expires_in = aDcoder.decodeDoubleForKey("expires_in")
        uid = aDcoder.decodeObjectForKey("uid") as! String
        
        expiresDate = aDcoder.decodeObjectForKey("expiresDate") as! NSDate
        name = aDcoder.decodeObjectForKey("name") as? String
        avatar_large = aDcoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
    ///  归档，aCoder 编码器，将对象转换成二进制数据保存到磁盘，和序列化很像
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")

        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey:"avatar_large")
        
        
    }
    
}
